/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.service.impl;

import java.io.IOException;
import java.io.OutputStream;

import com.cqcis.uip.base.framework.common.InterfaceLog;
import com.cqcis.uip.base.framework.utils.ByteBuffer;
import com.cqcis.uip.base.framework.utils.TimeUtil;

/**
 * 代理OutputStream, 加入记录功能
 * 
 * @author huangmy
 * @date   2008-11-3
 */
public class OutputStreamRecordBufferAdaptor extends OutputStream {
	private ByteBuffer buffer;
    private OutputStream os;
    private InterfaceLog intfLog;
    
	public OutputStreamRecordBufferAdaptor(OutputStream os, ByteBuffer buffer, InterfaceLog intfLog) {
		this.os = os;
		this.buffer = buffer;
		this.intfLog = intfLog;
	}
	
	private void recordSendTime() {
		if (this.intfLog.getSendTime() == null) {
			this.intfLog.setSendTime(TimeUtil.getCurrentTime());
		}
	}
	
	@Override
	public void write(int b) throws IOException {
		this.buffer.put((byte)b);
		recordSendTime();
		this.os.write(b);
	}
	
	@Override
	public void close() throws IOException {
		this.os.close();
	}
	
	@Override
	public boolean equals(Object obj) {
		return this.os.equals(obj);
	}
	
	@Override
	public void flush() throws IOException {
		this.os.flush();
	}
	
	@Override
	public int hashCode() {
		return this.os.hashCode();
	}
	
	@Override
	public void write(byte[] b) throws IOException {
		this.buffer.put(b);
		recordSendTime();
		this.os.write(b);
	}
	
	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		this.buffer.put(b, off, len);
		recordSendTime();
		this.os.write(b, off, len);
	}
	
	@Override
	public String toString() {
		return this.os.toString();
	}
}
